/*
 *
 *  *  Copyright (C) 2018  Wanghaobin<463540703@qq.com>
 *
 *  *  AG-Enterprise 企业版源码
 *  *  郑重声明:
 *  *  如果你从其他途径获取到，请告知老A传播人，奖励1000。
 *  *  老A将追究授予人和传播人的法律责任!
 *
 *  *  This program is free software; you can redistribute it and/or modify
 *  *  it under the terms of the GNU General Public License as published by
 *  *  the Free Software Foundation; either version 2 of the License, or
 *  *  (at your option) any later version.
 *
 *  *  This program is distributed in the hope that it will be useful,
 *  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  *  GNU General Public License for more details.
 *
 *  *  You should have received a copy of the GNU General Public License along
 *  *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

package cn.turing.firecontrol.auth.module.oauth.controller;

import cn.turing.firecontrol.auth.feign.IUserService;
import cn.turing.firecontrol.common.exception.auth.NonLoginException;
import cn.turing.firecontrol.common.msg.ObjectRestResponse;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

/**
 * @author ace
 * @create 2018/3/19.
 */
@Controller
public class UserController {
    private static final Logger _log = LoggerFactory.getLogger(UserController.class);

    @Value("${gitee.clientId}")
    private String CLIENTID;

    @Value("${gitee.clientSecret}")
    private String CLIENTSECRET;

    @Value("${gitee.redirectUri}")
    private String REDIRECTURI;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private IUserService iUserService;

    @RequestMapping("/user")
    @ResponseBody
    public Principal userInfo(Principal principal) {
        return principal;
    }

    /**
     * 生成授权地址
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public ObjectRestResponse login(){
        AuthRequest authRequest = getAuthRequest();
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        return ObjectRestResponse.success(authorizeUrl);
    }

    /**
     * 授权回调地址
     * @param callback
     * @throws IOException
     */
    @RequestMapping("/callback")
    @ResponseBody
    public void callback(AuthCallback callback) throws Exception {
        AuthRequest authRequest = getAuthRequest();
        // 访问gitee进行授权
        AuthResponse<AuthUser> login = authRequest.login(callback);
        if (login.getCode() != 2000) {
            throw new NonLoginException("gitee授权失败");
        }
        AuthUser authUser = login.getData();
        // 查询用户是否存在
        try {
            // 用户不存在时 会抛出异常
            iUserService.getUserInfoByUsername(authUser.getUsername());
        } catch (Exception e) {
            _log.error("用户不存在");

            BASE64Encoder encoder = new BASE64Encoder();
            // 默认使用git中的用户名作为账户名和密码 （git中的用户名是唯一的）
            String pass = authUser.getUsername();
            String encodePass = encoder.encode(pass.getBytes());
            String encodePassword = encoder.encode((encodePass+ "LJ7FXK5").getBytes());
            // 创建一个用户
            iUserService.addUser(authUser.getUuid(), authUser.getUsername(), authUser.getNickname(), null, encodePassword, null);
        }

        response.sendRedirect("http://127.0.0.1:9527/#/login");
    }

    /**
     * 创建Request
     * @return
     */
    private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId(CLIENTID)
                .clientSecret(CLIENTSECRET)
                .redirectUri(REDIRECTURI)
                .build());
    }
}
